package org.minuframework.dom4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.minuframework.core.ApplicationConfigurer;
import org.minuframework.lang.StringUtils;
import org.minuframework.utils.LocaleUitls;

public class XMLWriter{
    
    public static final String DEFAULT_XML_FOLDER = "Documents";
    public static final String DEFAULT_XML_NAME   = "dom4j.xml";
    
    public static boolean write(Document document){
        File file = new File(getDefaultXMLFile(), DEFAULT_XML_NAME);
        return writer(document, file);
    }
    
    public static boolean write(Document document, String pathname){
        if (StringUtils.isEmpty(pathname)) { return write(document); }
        return writer(document, new File(pathname));
    }
    
    public static boolean write(Document document, File file){
        if (file == null || file.isDirectory()) { return write(document); }
        return writer(document, file);
    }
    
    @SuppressWarnings("static-access")
    private static boolean writer(Document document, File file){
        boolean flag = true;
        
        org.dom4j.io.XMLWriter writer = null;
        try {
            FileWriter fileWriter = new FileWriter(file);
            OutputFormat format = new OutputFormat().createPrettyPrint();
            format.setEncoding(ApplicationConfigurer.DEFAULE_MINU_CHARSET);
            writer = new org.dom4j.io.XMLWriter(fileWriter, format);
            document.getRootElement();
            writer.write(document);
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return flag;
    }
    
    public static File getDefaultXMLFile(){
        String userhome = System.getProperty(LocaleUitls.USER_DIR);
        return new File(userhome, DEFAULT_XML_FOLDER);
    }
    
    public static void main(String[] args){
        /*
         * Document document = DocumentHelper.createDocument(); Element books =
         * document.addElement("books");
         * books.addComment("This is a test xml for dom4j"); Element book =
         * books.addElement("book"); book.addAttribute("show", "yes");
         * book.addAttribute("file", "enable"); Element title =
         * book.addElement("title"); title.addText("this is dom4j");
         * XMLWriter.write(document);
         */
        System.out.println(getDefaultXMLFile());
    }
    
}
